import os
import sys
import time
import ADS1256
import threading
import multiprocessing
import RPi.GPIO as GPIO

stepApul = 20  # A角电机频率
stepAdir = 21  # A角电机方向

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(stepApul, GPIO.OUT)
GPIO.setup(stepAdir, GPIO.OUT)

if sys.platform == "linux":
    os.system("clear")
elif sys.platform == "win32":
    os.system("cls")
dc = 0


def thread_1():
    global dc
    try:
        ADC = ADS1256.ADS1256()
        ADC.ADS1256_init()
        while True:
            ADC_Value = ADC.ADS1256_GetAll()
            print("0 ADC = %lf" % (ADC_Value[0]*5.0/0x7fffff),)
            print("1 ADC = %lf" % (ADC_Value[1]*5.0/0x7fffff),)
            print("2 ADC = %lf" % (ADC_Value[2]*5.0/0x7fffff),)
            print("3 ADC = %lf" % (ADC_Value[3]*5.0/0x7fffff),)
            print("4 ADC = %lf" % (ADC_Value[4]*5.0/0x7fffff),)
            print("5 ADC = %lf" % (ADC_Value[5]*5.0/0x7fffff),)
            print("6 ADC = %lf" % (ADC_Value[6]*5.0/0x7fffff),)
            print("7 ADC = %lf" % (ADC_Value[7]*5.0/0x7fffff),)
            sp = int((ADC_Value[3] * 5.0 / 0x7fffff) * 22)
            dc = int((ADC_Value[4] * 5.0 / 0x7fffff) * 22)
            # 这里的sp和dc都要作限幅,限制在0-99范围内
            print("%02d %02d" % (dc, sp))
            print("客户端摇杆输入信息")
            print("\33[12A")
    except:
        exit()


def thread_2():
    global dc
    print(dc)
    while dc > 71:
        GPIO.output(stepAdir, GPIO.HIGH)
        GPIO.output(stepApul, GPIO.HIGH)
        time.sleep(0.0005)
        GPIO.output(stepApul, GPIO.LOW)
        time.sleep(0.0005)


def main():
    t1 = threading.Thread(target=thread_1)
    t2 = threading.Thread(target=thread_2)
    t1.start()
    t2.start()
    t1.join()
    t2.join()


#t3 = threading.Thread(target=thread_3)
# threads.append(t3)
if __name__ == '__main__':
    main()
GPIO.cleanup()

# 共享全局变量
